#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

#define FILENAME "/home/tc/linux-course/lesson-进程间通信/Shmget/shmget.cpp"
#define PROJ_ID 0x6666
#define SIZE 4096

int main()
{
    key_t key = ftok(FILENAME, PROJ_ID);
    if (key < 0)
    {
        printf("ftok fail!\n");
        exit(1);
    }

    int shm = shmget(key, SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shm < 0)
    {
        printf("shmgrt fail!\n");
        exit(2);
    }

    std::cout << "key: " << key << endl;
    std::cout << "shm: " << shm << endl;
    // 共享内存被创建，两秒之后共享内存被移除，再两秒程序退出
    printf("attach begin!\n");
    sleep(2);
    char *mem = (char *)shmat(shm, NULL, 0);
    if (mem == (void *)-1) // 默认读写  关连不上
    {
        printf("attach fail!\n");
        exit(3);
    }
    printf("attach success!\n");

    printf("detach begin!\n");
    sleep(2);
    shmdt(mem); // 参数为地址
    printf("detach end!\n");

    sleep(2);

    shmctl(shm, IPC_RMID, NULL);
    // sleep(2);

    return 0;
}